<template>
  <Dialog :text="text" v-model:show="show" @submit="submit">
    <template v-slot:content>
      <ImageUpload @submit="uploadImage" />

      <div class="property">

	<span>价格: </span>
	<input type="number" v-model.number="price"/>

	<span>类别: </span>
	<select v-model="selected">
	  <template v-for="(option, index) in goodsTypes" :key="index">
	    <option :value="option.name">{{option.name}}</option>
	  </template>
	</select>

	<span>名称: </span>
	<input type="text" v-model="name"/>

	<span>库存: </span>
	<input type="number" v-model.number="stock"/>

	<span>介绍: </span>
	<textarea v-model="introduction"/>

      </div>

    </template>
  </Dialog>
</template>

<script lang="ts" setup>
 import { GoodsService, GoodsTypeService, ImageUploadService } from '@/service'
 import { inject, onMounted, PropType, ref } from '@vue/runtime-core'
 import Dialog from './Dialog.vue'
 import ImageUpload from './ImageUpload.vue'
 
 defineProps({
   text: String,
 })

 const emit = defineEmits(['submit'])
 const name = ref('')
 const price = ref(0)
 const stock = ref(0)
 const type = ref('')
 const introduction = ref('')
 
 const goodsTypes = ref<Array<GoodsType>>([])
 const selected = ref('')
 const show = ref(false)
 const shouldUpdate = inject<boolean>('shouldUpdate')

 let imageFile: File | null = null;
 
 function uploadImage(file: File) {
   imageFile = file
 }

 async function submit() {
   // use insert one
   // TODO how to upload image ?
   await ImageUploadService.upload(imageFile!)
   await GoodsService.insertOne({
     name: name.value,
     price: price.value,
     stock: stock.value,
     type: selected.value,
     introduction: introduction.value,
     src: imageFile!.name
   })

   shouldUpdate.value = true
 }

 onMounted(async () => {
   goodsTypes.value = await GoodsTypeService.findAll()
 })
</script>

<style lang="scss" scoped>
 div.property {
   display: grid;
   grid-template-columns: repeat(2, 100px);
 }

 label {
   display: block;
   margin-left: auto;
   margin-right: auto;
   width: 50%;
   span {
     width: 20%;
     float: left;
     text-align: right;
   }

   input {
     outline: 0;
     background: #f2f2f2;
     width: 70%;
     border: 0;
     margin: 0 0 15px;
     padding: 15px;
     box-sizing: border-box;
     font-size: 14px;
   }

 }
</style>